import { storage } from './base.js'
import { BASE_URL } from '@/config/app.config'

const handleResponse = (response) => {
  uni.hideLoading()
  if (!response) return
  switch (JSON.parse(response.data).state) {
    case 1:
      return response.data
    case 2:
      uni.showToast({
        title: response.data.message,
        icon: 'none'
      })
      break
    case 3:
      uni.showToast({
        title: response.data.message,
        icon: 'none'
      })
      break
    case 4:
      uni.showToast({
        title: '没有权限',
        icon: 'none'
      })
      break
    case 5:
      // 登录过期
      uni.showToast({
        title: '登录过期',
        icon: 'none'
      })
      uni.navigateTo({
        url: '/pages/account/login/login.vue'
      })
      break
  }
}

/**
 * 接收一个对象
 * {url, filePath,name,formData,success}
 * url: api地址
 * filePath:文件临时路径
 * name:文件对应的参数
 * formData:额外参数
 * success:成功处理函数
 * fail：失败处理函数
 * complete：完成处理函数
 */

export const uploadFileRequest = (params) => {
  const { url, filePath, name, formData, success, fail, complete } = params
  uni.showLoading({
    mask: true,
    title: ''
  })
  uni.uploadFile({
    url: BASE_URL + url,
    filePath: filePath,
    name,
    formData,
    header: {
      Authorization: storage.get('token')
    },
    success(res) {
      success(JSON.parse(res.data))
    },
    fail() {
      fail && fail()
    },
    complete(response) {
      handleResponse(response)
      complete && complete()
    }
  })
}
